<?php
/*
** etc: 用户模块
** author: deepe.xiao
** version: v0.1
*/

namespace app\controllers\Project_1_0;

use app\models\Project_1_0\User as MUser;

use Core\Controller;
use Exception;

class User extends Controller{


    //index.php?action=user&func=login
    //呈现登录页面
    function login(){
        $tp = loadLibrary("Mytp");
        $tp->tp("user/login");
    }
    //实现登录功能
    function signin(){
        if(isset($_POST['name'])){
            if(isset($_POST['password'])){

                 //登录功能,查询数据库
                $model = new MUser();
                $res = $model->searchUser($_POST['name'],$_POST['password']);

                if($res){
                    //将用户的信息存入会话中(大约存储30分钟)
                    $_SESSION["user"] = $res;
                    $this->success("登录成功","index.php?action=cases&func=index");
                }else{
                    $this->error("登录失败,请检查账号和密码");
                }
            }else{
                $this->error("抱歉,请输入密码");
            }
        }else{
            $this->error("抱歉,请输入用户名");
        }
    }

    //访问方式:index.php?action=user&func=index
    function index(){
        echo "这是登陆成功后的页面。。。";
    }






    /*****  下面代码是公司项目的示例   ****/
 	/* 输入参数:	
	 	user_account 播报号
	 	user_phone 手机号码
	 	user_weixin 微信号
	 	user_qq qq号码
	 	user_id 用户id
	 */

	 /* 返回信息 
	 code : 1  修改成功
	 code : -50008001 缺少参数播报号
	 code : -50008003 缺少参数微信号
	 code : -50008004 缺少参数qq号码
	 code : -50008005 缺少参数用户ID
	 code : -50008006 没有发现这个用户
	 */
	 //http://127.0.0.1/broadcast/?action=user&func=updateUserAllMessage&user_account=1&user_weixin=2&user_qq=1&user_id=1
	 function updateUserAllMessage(){
	 	$code = 0;
		$message = "";
		try{
				if( isset($_REQUEST['user_account']) ){
						if( isset($_REQUEST['user_weixin'])){
							if( isset($_REQUEST['user_qq']) ){
								if( isset($_REQUEST['user_id']) ){
									
                                    $user_account = mysql_escape_string( $_REQUEST['user_account'] );
									$user_weixin = mysql_escape_string( $_REQUEST['user_weixin'] );
									$user_qq = mysql_escape_string( $_REQUEST['user_qq'] );
									$user_id = mysql_escape_string( $_REQUEST['user_id'] );
									
									$userModel = $this->loadModel('user', true);
									$result = $userModel->searchUserByUserId( $user_id );
									if( $result ){
											$result_user = $result[0];//获取用户
											//判断是否修改了微信
											if($result_user['user_weixin'] != $user_weixin){
												$result_weixin = $userModel->isExistWeixin( $user_weixin );
												if($result_weixin)
												{
													$code = -50008007;
													$message = "Sorry , {$user_weixin} is already exists";
													throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );	
												}
											}
											
											$userModel->updateUserAllMessage( array(
												"user_account" => $user_account,
												"user_phone" => $result_user['user_phone'],//这里不修改手机号
												"user_weixin" => $user_weixin,
												"user_qq" => $user_qq,
												"user_id" => $user_id
											) );
											$code = 1;
											$message = "Success";
			        							echo json_encode( array( 'code' => $code , 'message' => $message ) ) ;
										
										}else{
											$code = -50008006;
											$message = "Sorry , not find User";
											throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
										}         
											
								}else{
									$code = -50008005;
									$message = "Sorry , Must input param user_id";
									throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
								}
								
							}else{
								$code = -50008004;
								$message = "Sorry , Must input param user_qq";
								throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
							}
						}else{
							$code = -50008003;
							$message = "Sorry , Must input param user_weixin";
							throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
						}
					
				}else{
					$code = -50008001;
					$message = "Sorry , Must input param user_account";
					throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
				}
			
		}catch (Exception $e) {   
			print $e->getMessage();  
		}

	 }
    // 修改用户手机号码
    //	?action=user&func=updateUserPhone&user_phone=13067566902&validate_code=382517&user_id=1
    function updateUserPhone() {
        try{
            if (isset($_REQUEST['user_id'])) {
                if (isset($_REQUEST['validate_code'])) {
                    if (time() <= $_SESSION['messageOutTime']) {
                        if ($_SESSION['messageRandNumber'] == $_REQUEST['validate_code']) {
                            unset($_SESSION['messageRandNumber']);
                            if (isset($_REQUEST['user_phone'])) {

                                $user_phone = mysql_escape_string($_REQUEST['user_phone']);
                                $user_id = mysql_escape_string( $_REQUEST['user_id'] );

                                if (!$this -> isMobile($user_phone)) {
                                    $code = -50007008;
                                    $message = "Sorry , Phone number format is not correct";
                                    throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                                }

                                $userModel = $this -> loadModel('user', true);
                                $result = $userModel -> searchUserByUserId($user_id);
                                if ($result) {
                                    $result_user = $result[0];
                                    //判断修改手机号码：如果手机号码不一致，就需要判断手机号是否存在了
                                    if ($result_user['user_phone'] != $user_phone) {
                                        //判断要修改的手机号是否已经存在，已经存在则不能进行修改
                                        $result_phone = $userModel -> isExistPhone($user_phone);
                                        if ($result_phone) {
                                            $code = -50007007;
                                            $message = "Sorry , {$user_phone} is already exists";
                                            throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                                        }
                                    }
                                    $userModel -> updateUserAllMessage(array(
                                    "user_account" => $result_user['user_account'],
                                    "user_phone" => $user_phone,
                                    "user_weixin" => $result_user['user_weixin'],
                                    "user_qq" => $result_user['user_qq'],
                                    "user_id" => $user_id
                                    ));
                                    $code = 1;
                                    $message = "Success";
                                    echo json_encode(array('code' => $code, 'message' => $message));
                                } else {
                                    $code = -50007006;
                                    $message = "Sorry , not find User";
                                    throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                                }
                            } else {
                                $code = -50007005;
                                $message = "Sorry ,  Must input param user_phone";
                                throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                            }
                        } else {
                            $code = -50007004;
                            $message = "Sorry , validate is error";
                            throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                        }
                    } else {
                        $code = -50007003;
                        $message = "Sorry , validate out of time";
                        throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                    }
                } else {
                    $code = -50007002;
                    $message = "Sorry , Must input param validate_code";
                    throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
                }
            } else {
                $code = -50007001;
                $message = "Sorry , Must input param user_id";
                throw new Exception(json_encode(array('code' => $code, 'message' => $message)));
            }

        }catch (Exception $e) {
            print $e->getMessage();
        }

    }

	//个人信息
	//http://127.0.0.1/broadcast/?action=user&func=userMessage&user_id=1
	function userMessage(){
		$code = 0;
		$message = "";
		try{
			if( isset($_REQUEST['user_id']) ){
				
				$user_id = mysql_escape_string( $_REQUEST['user_id'] );
				$userModel = $this->loadModel('user', true);
				$result = $userModel->searchUserByUserId( $user_id );
				
				if($result)
				{
					$code = 1;
		        		echo json_encode( array( 'code' => $code , 'message' => $result ) ) ;
				}else{
					$code = -50005002;
					$message = "Sorry , Must input param null";
					throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
					
				}
			}else{
				$code = -50005001;
				$message = "Sorry , Must input param user_id";
				throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
			}

		} catch (Exception $e) {   
			print $e->getMessage();  
		}
	}

	//最后一次登录信息
	//http://127.0.0.1/broadcast/?action=user&func=userLastloginMessage&user_phone=13067566902
	function userLastloginMessage(){
		$code = 0;
		$message = "";
		try{
			
			if( isset( $_REQUEST['user_phone'] )){
				$user_phone = mysql_escape_string( $_REQUEST['user_phone'] );
				$userModel = $this->loadModel('user', true);
				$result = $userModel->searchUserLastLogin( $user_phone );

				$code = 1;
		        echo json_encode( array( 'code' => $code , 'message' => $result ) ) ;
				
			}else{
				$code = -50004001;
				$message = "Sorry , Must input param user_account";
				throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );		
			}
			
			

		} catch (Exception $e) {   
			print $e->getMessage();  
		}	
	}

	//修改密码
	//pwd,newPwd,reNewPwd
	//http://127.0.0.1/broadcast/?action=user&func=updateModifyPassword&user_phone=xzp&pwd=123456&newPwd=123456&reNewPwd=123456
	function updateModifyPassword(){
		$code = 0;
		$message = "";
		try{
				validateToken( $_REQUEST );
				if( isset( $_REQUEST['pwd'] )&&isset( $_REQUEST['user_phone'] )){
					if( isset( $_REQUEST['newPwd'] ) && isset($_REQUEST['reNewPwd']) ){
						
						$newUserPassword = mysql_escape_string( $_REQUEST['newPwd'] );
						$reNewPassword = mysql_escape_string( $_REQUEST['reNewPwd'] );

						if( $newUserPassword == $reNewPassword ){
//							$buyer = $_SESSION['buyer'];//后期应该使用sign签名取用户id
//							$buyer_id = $buyer[0]['buyer_id'];
							$user_phone = mysql_escape_string( $_REQUEST['user_phone'] );
							
							
							$loginModel = $this->loadModel('login', true);
		        				$isResult = $loginModel->isExistUser( $user_phone,'');

							if( !empty($isResult) ){
								$userPassword = mysql_escape_string( $_REQUEST['pwd'] );
								$userModel = $this->loadModel('user', true);
								$result = $userModel->searchUserPassword( $user_phone, $userPassword );
								
								if( $result ){
									$modifyResult = $userModel->updateUserPassword( $user_phone, $newUserPassword );
									if( $modifyResult ){
										$code = 1;
										$message = "Success";
			        						echo json_encode( array( 'code' => $code , 'message' => $message ) ) ;
									}
	
								}else{
									$code = -50003005;
									$message = "Sorry , input param password not equal success";
									throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );		
								}
							}else{
								$code = -50003004;
								$message = "Sorry ,".$user_phone." not exists";
								throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );
							}
						}else{
							$code = -50003003;
							$message = "Sorry , input param newPwd not equal reNewPwd";
							throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );		
						}
					}else{
						$code = -50003002;
						$message = "Sorry , Must input param newPwd or reNewPwd";
						throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );		
					}
				}else{
					$code = -50003001;
					$message = "Sorry , Must input param user_pwd or user_phone";
					throw new Exception(  json_encode( array( 'code' => $code , 'message' => $message ) ) );	
				}
			

		} catch (Exception $e) {   
			print $e->getMessage();  
		}
	}

	
	

	


	/**
	 * 验证手机号是否正确
	 * @author Deepe
	 * @param INT $mobile
	 */
	 function isMobile($mobile) {
	    if (!is_numeric($mobile)) {
	        return false;
	    }
	    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
	 }
	

}
		